<?php

/**
 * apply actions.
 *
 * @package    lomejorde
 * @subpackage apply
 * @author     Your name here
 * @version    SVN: $Id: actions.class.php 23810 2009-11-12 11:07:44Z Kris.Wallsmith $
 */

require_once(sfConfig::get('sf_plugins_dir').'/sfDoctrineApplyPlugin/modules/sfApply/lib/BasesfApplyActions.class.php');
require_once(sfConfig::get('sf_lib_dir').'/vendor/EpiFramework/EpiCurl.php');
require_once(sfConfig::get('sf_lib_dir').'/vendor/EpiFramework/EpiOAuth.php');
require_once(sfConfig::get('sf_lib_dir').'/vendor/EpiFramework/EpiTwitter.php');

class applyActions extends BasesfApplyActions
{
    public function executeApplyTwitter(sfWebRequest $request)
    {
        $twitter = new Epitwitter(sfConfig::get('app_twitter_consumer_key'), sfConfig::get('app_twitter_consumer_secret'));
        
        $user = $this->getUser();
        
        if($request->getParameter('oauth_token') || ($user->hasAttribute('oauth_token') && $user->hasAttribute('oauth_token_secret'))) {
            // user accepted access
            if(!$user->hasAttribute('oauth_token') || !$user->hasAttribute('oauth_token_secret')) {
                // user comes from twitter
                $twitter->setToken($request->getParameter('oauth_token'));
                
                $token = $twitter->getAccessToken();
                
                $user->setAttribute('oauth_token', $token->oauth_token);
                $user->setAttribute('oauth_token_secret', $token->oauth_token_secret);
                $twitter->setToken($token->oauth_token, $token->oauth_token_secret);
            } else {
                // user switched pages and came back or got here directly, stilled logged in
                $twitter->setToken($user->getAttribute('oauth_token'),$user->getAttribute('oauth_token_secret'));
            }
            
            $twitter_data = Doctrine::getTable('TwitterData')->findOneByOauthToken($user->getAttribute('oauth_token'));
            
            if(!$twitter_data){
                $twitter_info= $twitter->get_accountVerify_credentials();
                
                $user_new = new sfGuardUser();
                
                $user_new->setEmailAddress($twitter_info->screen_name.'@twitter.com');
                
                $user_new->setPassword($twitter_info->screen_name.'@twitter.com');
                
                $user_new->setUsername($twitter_info->screen_name);
                
                $user_new->setHqhId(md5($user_new->getEmailAddress().time().$user_new->getUsername()));
                
                $user_new->save();
                
                $user_new_profile = new sfGuardUserProfile();
                
                $user_new_profile->setUser($user_new);
                
                $user_new_profile->setEmail($twitter_info->screen_name.'@twitter.com');
                
                $user_new_profile->setFullname($twitter_info->name);
                
                $user_new_profile->save();
                
                $twitter_data = new TwitterData();
                
                $twitter_data->setUser($user_new);
                
                $twitter_data->setOauthToken($user->getAttribute('oauth_token'));
                
                $twitter_data->setOauthTokenSecret($user->getAttribute('oauth_token_secret'));
                
                $twitter_data->save();
                
                $user->signin($user_new, true);
            } else {
                $user->signin($twitter_data->getUser(), true);
            }

            $signinUrl = sfConfig::get('app_sf_guard_plugin_success_signin_url', $user->getReferer($request->getReferer()));

            $this->redirect('' != $signinUrl ? $signinUrl : '@homepage');
        } else { // user denied access or not logged in
            $this->redirect('/');
        }
    }
    
    public function executeApplyFacebook(sfWebRequest $request)
    {        
        $fbconfig = array();
        $fbconfig['appid' ]     = sfConfig::get('app_facebook_appid');
        $fbconfig['secret']     = sfConfig::get('app_facebook_secret');
        $fbconfig['baseurl']    = sfContext::getInstance()->getRouting()->generate('apply_facebook', array(), true);
        
        $fb_user = null; //facebook user uid
        
        try {
            include_once sfConfig::get('sf_lib_dir').'/vendor/PHP-SDK-3.0-Graph-API-Facebook/facebook.php';
        } catch(Exception $o) {
            error_log($o);
        }
        
        // Create our Application instance.
        $facebook = new Facebook(array(
            'appId'  => $fbconfig['appid'],
            'secret' => $fbconfig['secret'],
            'cookie' => true,
        ));
        
        $fb_user = $facebook->getUser();

        //if user is logged in and session is valid.
        if ($fb_user){
            //get user basic description
            $fb_user_info = $facebook->api("/".$fb_user);
        } else { // user denied access or not logged in
            $this->redirect('/');
        }
        
        $user = $this->getUser(); // LoMejorDe User!!!
        
        $facebook_data = Doctrine::getTable('FacebookData')->findOneByFbUserId($fb_user);
        
        if(!$facebook_data){
            
            $stored_user = Doctrine::getTable('sfGuardUser')->findOneByEmailAddress($fb_user_info['email']);
            
            if(!$stored_user){
                $user_new = new sfGuardUser();

                $user_new->setFirstName($fb_user_info['first_name']);

                $user_new->setLastName($fb_user_info['last_name']);

                $user_new->setEmailAddress($fb_user_info['email']);

                $user_new->setPassword($fb_user_info['email']);
                
                $username = explode('@', $fb_user_info['email']);
                
                $user_new->setUsername((isset($fb_user_info['username']) ? $fb_user_info['username'] : $username[0]).'_fbusername');

                $user_new->setHqhId(md5($user_new->getEmailAddress().time().$user_new->getUsername()));

                $user_new->save();

                $user_new_profile = new sfGuardUserProfile();

                $user_new_profile->setUser($user_new);

                $user_new_profile->setEmail($fb_user_info['email']);

                $user_new_profile->setFullname($fb_user_info['name']);

                $user_new_profile->save();

                $facebook_data = new FacebookData();

                $facebook_data->setUser($user_new);

                $facebook_data->setFbUserId($fb_user);

                $facebook_data->setAccessToken($facebook->getAccessToken());

                $facebook_data->save();
                
                $user->signin($user_new, true);
            } else {
                $facebook_data = new FacebookData();

                $facebook_data->setUser($stored_user);

                $facebook_data->setFbUserId($stored_user);

                $facebook_data->setAccessToken($facebook->getAccessToken());

                $facebook_data->save();
                
                $user->signin($stored_user, true);
            }
        } else {
            $user->signin($facebook_data->getUser(), true);
        }

        $signinUrl = sfConfig::get('app_sf_guard_plugin_success_signin_url', $user->getReferer($request->getReferer()));

        $this->redirect('' != $signinUrl ? $signinUrl : '@homepage'); 
    }
    
    public function executeApply(sfRequest $request)
    {
        $this->form = $this->newForm('minifiedApplyForm');
        if ($request->isMethod('post')){
            $this->form->bind($request->getParameter('minifiedApply'));
            if ($this->form->isValid()){
                $guid = "n" . self::createGuid();
                $this->form->setValidate($guid);
                $this->form->save();
                try {
                    $profile = $this->form->getObject();
                    $this->sendVerificationMail($profile);
                    return 'After';
                } catch (Exception $e) {
                    $profile = $this->form->getObject();
                    $user = $profile->getUser();
                    $user->delete();
                    throw $e;
                    // You could re-throw $e here if you want to 
                    // make it available for debugging purposes
                    return 'MailerError';
                }
            }
        }
    }
}
